//
//  LXHomeViewController.m
//  微博
//
//  Created by imera on 15-9-10.
//  Copyright (c) 2015年 imera. All rights reserved.
//

#import "LXHomeViewController.h"
#import "UIButton+LX.h"
#import "AFNetworking.h"
#import "LXAcount.h"
#import "LXStatus.h"
#import "MJExtension.h"
#import "LXUser.h"
#import "UIImageView+WebCache.h"
#import "LXStatusFrame.h"
#import "LXTableViewCell.h"
#import "MJRefresh.h"

@interface LXHomeViewController ()

@property (nonatomic, strong) NSMutableArray *statusFrameArr;

@end

@implementation LXHomeViewController

- (void)setStatusFrameArr:(NSMutableArray *)statusFrameArr
{
    if(_statusFrameArr == nil){
        _statusFrameArr = [NSMutableArray array];
    };
    _statusFrameArr = statusFrameArr;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self setupTabBar];
    
    [self setupRefreshControl];
    
    [self setupTitleView];
}

/**
 *  初始化标题
 */
- (void)setupTitleView
{
    //1.创建请求管理对象
    AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    
    params[@"access_token"] = [LXAcount Acount].access_token;
    params[@"uid"] = @([LXAcount Acount].uid);

    [mgr GET:@"https://api.weibo.com/2/users/show.json" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
        LXUser *user = [LXUser objectWithKeyValues:responseObject];
        self.title = user.screen_name;
        
        //保存用户昵称
        LXAcount *account = [LXAcount Acount];
        account.name = user.screen_name;
        [LXAcount saveAcount:account];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError * error) {
        NSLog(@"请求失败");
    }];
}

/**
 *  初始化刷新控件
 */
- (void)setupRefreshControl
{
    //下拉刷新控件
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(refreshNewData)];
    [header beginRefreshing];
    self.tableView.mj_header = header;
    
    //上拉刷新控件
    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(refreshData)];
    footer.automaticallyRefresh = NO;
    self.tableView.mj_footer = footer;
}

- (void)refreshData
{
    //1.创建请求管理对象
    AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    
    params[@"access_token"] = [LXAcount Acount].access_token;
    LXStatusFrame *statusFrame = [self.statusFrameArr lastObject];
    params[@"max_id"] = statusFrame.status.idstr;
    params[@"count"] = @(5);
    
    [mgr GET:@"https://api.weibo.com/2/statuses/friends_timeline.json" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
        //创建微博模型数组
        NSArray *statusArr = [LXStatus objectArrayWithKeyValuesArray:responseObject[@"statuses"]];
        
        //创建Frame模型数组
        NSMutableArray *statusFrameArr = [NSMutableArray array];
        for(LXStatus *status in statusArr){
            LXStatusFrame *statusFrame = [[LXStatusFrame alloc]init];
            statusFrame.status = status;
            [statusFrameArr addObject:statusFrame];
        }
        [statusFrameArr removeObjectsAtIndexes:[NSIndexSet indexSetWithIndex:0]];
        [self.statusFrameArr addObjectsFromArray:statusFrameArr];
    
        [self.tableView reloadData];
        
        [self.tableView.mj_footer endRefreshing];
    } failure:^(AFHTTPRequestOperation *operation, NSError * error) {
        [self.tableView.mj_footer endRefreshing];
    }];
}

/**
 *  刷新数据
 */
- (void)refreshNewData
{
    //1.创建请求管理对象
    AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    
    params[@"access_token"] = [LXAcount Acount].access_token;
    params[@"count"] = @(5);
    LXStatusFrame *statusFrame = [self.statusFrameArr firstObject];
    if(statusFrame.status.idstr){
        params[@"since_id"] = statusFrame.status.idstr;
    }
    
    [mgr GET:@"https://api.weibo.com/2/statuses/friends_timeline.json" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
        //创建微博模型数组
        NSArray *statusArr = [LXStatus objectArrayWithKeyValuesArray:responseObject[@"statuses"]];
        
        //创建Frame模型数组
        NSMutableArray *statusFrameArr = [NSMutableArray array];
        for(LXStatus *status in statusArr){
            LXStatusFrame *statusFrame = [[LXStatusFrame alloc]init];
            statusFrame.status = status;
            [statusFrameArr addObject:statusFrame];
        }
        
        NSMutableArray *tempArr = [NSMutableArray array];
        [tempArr addObjectsFromArray:statusFrameArr];
        [tempArr addObjectsFromArray:self.statusFrameArr];
        self.statusFrameArr = tempArr;
        
        [self.tableView reloadData];
        [self.tableView.mj_header endRefreshing];
        
        //提示用户新微博数目
        [self showNewStatusCount:statusFrameArr.count];
    } failure:^(AFHTTPRequestOperation *operation, NSError * error) {
        NSLog(@"请求失败");
        [self.tableView.mj_header endRefreshing];
    }];
}

- (void)showNewStatusCount:(NSInteger)count
{
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.navigationController.view insertSubview:btn belowSubview:self.navigationController.navigationBar];
    
    //设置图片和文字
    btn.userInteractionEnabled = NO;
    [btn setBackgroundImage:[UIImage resizeWithName:@"timeline_new_status_background"] forState:UIControlStateNormal];
    [btn setTitleColor:[UIColor orangeColor] forState:UIControlStateNormal];
    if(count){
        [btn setTitle:[NSString stringWithFormat:@"共有%d条新微博",(int)count] forState:UIControlStateNormal];
    }else{
        [btn setTitle:[NSString stringWithFormat:@"没有新微博数据"] forState:UIControlStateNormal];
    }
    
    //设置frame
    CGFloat btnX = 0;
    CGFloat btnW = self.view.frame.size.width;
    CGFloat btnH = 30;
    CGFloat btnY = 64 - btnH;
    btn.frame = CGRectMake(btnX, btnY, btnW, btnH);
    
    //设置动画提示
    [UIView animateWithDuration:0.7 animations:^{
        btn.transform = CGAffineTransformMakeTranslation(0, btnH);
    } completion:^(BOOL finished) {
        [UIView animateWithDuration:0.7 delay:1 options:UIViewAnimationOptionCurveLinear animations:^{
            btn.transform = CGAffineTransformIdentity;
        } completion:^(BOOL finished) {
            [btn removeFromSuperview];
        }];
    }];
}

/**
 *  初始化TabBar
 */
- (void)setupTabBar
{
    //左边按钮
    self.navigationItem.leftBarButtonItem = [UIButton initWithIcon:@"navigationbar_friendsearch" highIcon:@"navigationbar_friendsearch_highlighted" target:self action:@selector(friend)];
    //右边按钮
    self.navigationItem.rightBarButtonItem = [UIButton initWithIcon:@"navigationbar_pop" highIcon:@"navigationbar_pop_highlighted" target:self action:@selector(pop)];
}

/**
 *  左边按钮点击事件
 */
- (void)friend
{
    NSLog(@"friend");
}

/**
 *  右边按钮点击事件
 */
- (void)pop
{
    NSLog(@"pop");
}

#pragma mark - Table view data source
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    return self.statusFrameArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // 1.创建cell
    LXTableViewCell *cell = [LXTableViewCell cellWithTableView:tableView];
    
    //取出模型数据
    LXStatusFrame *statusFrame = self.statusFrameArr[indexPath.row];
    
    cell.statusF = statusFrame;
    
    return cell;

}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    LXStatusFrame *statusFrame = self.statusFrameArr[indexPath.row];
    
    return statusFrame.cellHeight;

}

@end
